package edu.gatech.startrader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.thoughtworks.xstream.XStream;

import edu.gatech.startrader.trade.TradeGood;
import edu.gatech.startrader.universe.Planet;

/**
 * SaveState Class
 * This class sets up the save state
 * @author Team Bamf (Team 30)
 * @version : 1.0
 */
public class SaveState {

	/**
	 * Xstream Object used to Save and Load the game as an XML File
	 */
	private static final XStream XSTREAM = new XStream();

	/**
	 * The game that was saved
	 */
	private final Game savedInformation;
	
	static
	{
		XSTREAM.alias("TradeGood", TradeGood.class);
		XSTREAM.alias("Plant", Planet.class);
	}
	
	/**
	 * Private Constructor of the SaveState objects
	 * @param gameInfo the game that was saved
	 */
	private SaveState(Game gameInfo){
		savedInformation = gameInfo;
	}
	
	/**
	 * SaveState Constructor
	 * This constructor sets up the default save state
	 * @param gameFile the file to be loaded from
	 * @return saved game
	 */
	public static SaveState load(File gameFile) {
		if(!gameFile.exists()) {
			throw new IllegalArgumentException("File does not exist. Game not loaded");
		}
		return new SaveState((Game) XSTREAM.fromXML(gameFile));
	}
	
	/**
	 * saveTo method
	 * This method saves the game to a selected file location
	 * @param file the file to save to
	 * @param game the game to be saved
	 */
	public static void saveTo(File file, Game game) {
		final String xml = XSTREAM.toXML(game);
		OutputStream fop = null;
		try {
			fop = new FileOutputStream(file);
			if(file != null && !file.exists()) {
				boolean check = file.createNewFile();
				if(!check) {
					throw new IOException("Error: Save File cannot be created");
				}
			}
			final byte[] fileInBytes = xml.getBytes();
			fop.write(fileInBytes);
			fop.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fop != null) {
					fop.close();
				}
			}  catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * getsaveInfo method
	 * This method returns the information of a saved game
	 * @return Game returns the saved Game
	 */
	public Game getSaveInfo() {
		return savedInformation;
	}
	
	/**
	 * Returns the SaveState object as a String
	 * @return the object as a String
	 */
	public String toString() {
		return savedInformation.toString();
	}
}
